<template>
  <div>
    <NavCom
      :list="tabs"
      :active="activeName"
      style="padding-left: 5px"
      @change="handleTabClick"
    >
      <el-button
        v-if="activeName === 1"
        slot="button"
        size="small"
        type="primary"
        style="margin: 8px"
        @click="addTags"
        >{{ $t('common.addRows') }}</el-button
      >
    </NavCom>
    <div v-show="activeName === 0" style="padding: 10px">
    </div>
    <div v-show="activeName === 1" style="padding: 10px">
      <el-table ref="table" :data="InstructionsList" stripe>
        <el-table-column prop="title" :label="$t('order.inst')" width="100px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <div v-if="scope.row.editRows">
              <el-select
                v-model="scope.row.title"
                :placeholder="$t('common.placeholderSelect')"
                @change="selectChange(scope.row, scope.$index)"
              >
                <el-option
                  v-for="item in InstructionOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.label"
                >
                </el-option>
              </el-select>
            </div>
            <div v-else>
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="template" :label="$t('common.temp')" width="120px">
          <template slot-scope="scope">
            <el-link
              v-if="scope.row.template"
              type="primary"
              :href="scope.row.template"
            >
              {{ $t("common.downloadTemp") }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="fileList" :label="$t('common.fileName')" width="320px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <div v-if="scope.row.editRows">
              <el-upload
                v-if="scope.row.template || scope.row.files"
                :file-list="fileList"
                :auto-upload="true"
                :action="uploadFileUrl"
                accept=".xlsx,.xls"
                :data="{ row: scope.row }"
                :on-error="handleUploadError"
                :on-success="handleUploadSuccess(scope.row, files)"
                :headers="headers"
                style="text-align: left"
              >
                <el-button v-if="!scope.row.files" type="text">{{ $t('common.upload') }}</el-button>
                <div v-if="scope.row.files">
                  <span>{{ scope.row.fileName || scope.row.receiptFile || filterFileName(scope.row.files) }}</span>
                  <el-button type="text">重新上传</el-button>
                </div>
                <el-tooltip
                  v-else
                  class="item"
                  effect="dark"
                  :content="scope.row.fileName"
                  placement="bottom-end"
                >
                  <span>{{ scope.row.fileName || scope.row.receiptFile || filterFileName(scope.row.fileName) }}</span>
                </el-tooltip>
              </el-upload>
            </div>
            <el-tooltip
              v-if="scope.row.files && scope.row.editRows == false"
              class="item"
              effect="dark"
              :content="scope.row.files"
              placement="bottom-end"
            >
              <span>{{ scope.row.fileName || scope.row.receiptFile || filterFileName(scope.row.files) }}</span>
            </el-tooltip>
            <div v-if="scope.row.files">
              <el-tag size="mini" type="success" style="margin-right: 10px" @click="viewImg(scope.row.files, scope.$index)">
                <i class="el-icon-view" />
                查看
              </el-tag>
              <el-tag size="mini" @click="downLoad(scope.row.files, scope.row.fileName || scope.row.receiptFile)">
                <i class="el-icon-download" />
                下载
              </el-tag>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="status" :label="$t('common.status')" />
        <el-table-column prop="remarks" :label="$t('common.remark')">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <div v-if="scope.row.editRows">
              <el-input v-model="scope.row.remarks"></el-input>
            </div>
            <div v-else>
              {{ scope.row.remarks }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="operation" :label="$t('common.operation')">
          <template slot-scope="scope">
            <!-- <div v-if="scope.row.files"> -->
            <div>
              <el-button
                v-if="scope.row.edit == true"
                type="text"
                @click="editRowsOperation(scope.row)"
                >{{ $t('common.edit') }}</el-button
              >
              <div v-else>
                <el-button type="text" @click="saveEditRows(scope.row)"
                  >{{ $t('common.save') }}</el-button
                >
                <el-button type="text" @click="cancelSave(scope.row)"
                  >{{ $t('common.cancel') }}</el-button
                >
              </div>
              <el-button
                v-if="scope.row.edit == true"
                type="text"
                @click="delTags(scope.row, scope.row.id)"
                >{{ $t('common.del') }}</el-button
              >
            </div>
            <!-- <span v-else>-</span> -->
          </template>
        </el-table-column>
      </el-table></div>
  </div>
</template>
<script>
import { getToken } from "@/utils/auth";
import { getInstruct, addInstruct, changeInstruct, delInstruct } from "@/api/order/index.js";
import NavCom from "@/components/Nav/detail.vue";
import FormComponents from "@/components/FormComponents/index.vue";
export default {
  components: { NavCom, FormComponents },
  props: {
    ruleFrom: {
      type: Object,
      default: () => {
        return {};
      },
    },
    id: {
      type: String | Number,
      default: null,
    },
  },
  data() {
    return {
      tabs: [
        // { label: "入库单信息", active: 0 },
        { label: this.$t('order.insList'), active: 1 },
      ],
      activeName: 1,
      InstructionOptions: [
        {
          label: this.$t('inst.InstructionOptions.LABELING'),
          value: "LABELING",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx",
        },
        {
          label: this.$t('inst.InstructionOptions.CHANGEBOX'),
          value: "CHANGEBOX",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.LABELCHANGE'),
          value: "LABELCHANGE",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xlsx/7239d6f501bb4358aedb60ab2646160c/换标登记表.xlsx",
        },
        {
          label: this.$t('inst.InstructionOptions.DSORDER'),
          value: "DSORDER",
          fileName: "",
          fileUrl:
            "https://zjyg-yt.oss-cn-hangzhou.aliyuncs.com/scm/upload/20230921/xls/092b9403620e4be797de7e4aa3232713/DS订单拣货标模板.xls",
        },
        {
          label: this.$t('inst.InstructionOptions.RTVPICKUP'),
          value: "RTVPICKUP",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.CHANGEPRODUCT'),
          value: "CHANGEPRODUCT",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.DELIVERYFEE'),
          value: "DELIVERYFEE",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.stockAgeFee'),
          value: "stockAgeFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.warehouseOperationFee'),
          value: "warehouseOperationFee",
          fileName: "",
          fileUrl: "",
        },
        {
          label: this.$t('inst.InstructionOptions.materialCost'),
          value: "materialCost",
          fileName: "",
          fileUrl: "",
        }
      ],
      InstructionsList: [],
      fileList: [],
      uploadFileUrl: process.env.VUE_APP_BASE_API + "/upload/uploadFile", // 上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken(),
      },
    };
  },
  computed: {
    column() {
      const base = [
        { prop: "memberUsername", label: this.$t('customer.name'), type: "input", col: 8 },
        { prop: "receiverName", label: this.$t('order.consignee'), type: "input", col: 8 },
        { prop: "receiverPhone", label: this.$t('order.consigneePhone'), type: "input", col: 8 },
        { prop: "receiverEmail", label: this.$t('order.consigneeEmail'), type: "input", col: 8 },
        { prop: "receiverPostCode", label: this.$t('common.PostalCode'), type: "input", col: 8 },
        { prop: "receiverProvince", label: this.$t('common.province'), type: "input", col: 8 },
        { prop: "receiverCity", label: this.$t('common.city'), type: "input", col: 8 },
        {
          prop: "receiverDetailAddress",
          label: this.$t('order.consigneeAddress'),
          type: "input",
          col: 24,
        },
      ];
      return { base };
    },
  },
  watch: {
    id: {
      handler(v) {
        this.getList(v)
      },
      immediate: true,
    },
  },
  methods: {
    handleTabClick(v) {
      this.activeName = v.active;
      if (this.activeName === 1) {
        this.getList(this.id);
      }
    },
    // 单行编辑操作
    editRowsOperation(rows) {
      rows.editRows = true;
      rows.edit = false;
    },
    addTags() {
      this.InstructionsList.push({
        edit: false,
        editRows: true,
        instructions: "",
        title: "",
        template: "",
        files: "",
        fileName: "",
        remarks: "",
      });
    },
    selectChange(row, index) {
      const url = this.InstructionOptions.find(
        (a) => a.label === row.title
      ).fileUrl;
      if (url) {
        this.$refs.table.tableData[index].template = url;
      } else {
        this.$refs.table.tableData[index].template = null;
      }
    },
    delTags(rows, id) {
      delInstruct(id).then(res=>{
        if(res) {
          this.$message.success(this.$t('common.succcessInfo'))
          setTimeout(() => {
            this.getList(this.id);
          }, 300);
        }
      })
    },
    // 单行保存
    saveEditRows(rows) {
      const params = {
        ...rows,
        remarks: rows.remarks,
      }
      const api = rows.id ? changeInstruct : addInstruct
      // 新建时候把orderID塞进去
      params.orderId = this.id
      api({...params}).then((res) => {
        if (res) {
          this.$message.success(this.$t('common.succcessInfo'));
          this.cancelSave(rows);
          setTimeout(() => {
            this.getList(this.id);
          }, 300);
        }
      });
    },
    cancelSave(rows) {
      // 单行编辑状态
      rows.editRows = false;
      rows.edit = true;
      setTimeout(() => {
        this.getList(this.id);
      }, 300);
    },
    handleUploadError() {
      this.uploadLoading = false;
      this.fileList = [];
      this.$message({
        type: "error",
        message: this.$t('common.failedMsg'),
      });
    },
    handleUploadSuccess(row) {
      return (response, file, fileList) => {
        // 将上传的文件信息赋值给相应行的对象
        row.fileName = file.name;
        row.receiptFile = file.name
        row.files = file.response || file.response.data;
      };
    },
    filterFileName(fileName) {
      const maxLength = 22; // 最大长度，包括省略号
      let truncatedName = fileName;
      if (fileName && fileName.length > maxLength) {
        const prefixLength = Math.floor((maxLength - 3) / 2); // 前缀长度
        const suffixLength = maxLength - prefixLength - 3; // 后缀长度
        const prefix = fileName.substr(0, prefixLength);
        const suffix = fileName.substr(fileName.length - suffixLength);
        truncatedName = `${prefix}...${suffix}`;
        return truncatedName;
      }
    },
    /* 查看附件 */
    viewImg(url, index) {
      const fileType = url.substring(url.lastIndexOf(".")).toLowerCase();
      // /* 图片 */
      if ([".jpg", ".png", ".jpeg", ".gif", ".webp"].includes(fileType)) {
        this.dialogViewFileImg = true;
        this.initialIndex = index;
        this.viewerImgList = this.tableData.map((f) => {
          return f.filePath;
        });
      } else {
        window.open('https://view.officeapps.live.com/op/view.aspx?src=' + url, '_blank')
      }
    },
    /* 下载附件 */
    downLoad(url, name) {
      const a = document.createElement('a')
      a.href = url
      a.download = name // 下载后文件名
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click() // 点击下载
      document.body.removeChild(a) // 下载完成移除元素
    },
    getList(v) {
      getInstruct({ orderId: v }).then((res) => {
        this.InstructionsList = res.content.map((r) => {
          return {
            // 单行编辑状态
            editRows: false,
            edit: true,
            ...r,
          };
        });
        this.$forceUpdate()
      });
    },
  },
};
</script>
